import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Inject,
} from '@nestjs/common';
import { Response, Request } from 'express';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';
import { getReqMainInfo } from '@/utils/Logutils';

@Catch()
export default class SystemUnifyExceptionFilter implements ExceptionFilter {
  constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger) {}

  catch(caughtException: any, host: ArgumentsHost) {
    const context = host.switchToHttp();
    const request = context.getRequest<Request>();
    const response = context.getResponse<Response>();

    let status = HttpStatus.INTERNAL_SERVER_ERROR;
    let errorMessage = '系统异常';
    let responseContent = caughtException;

    if (typeof caughtException === 'object') {
      const exceptionResponse = typeof caughtException.getResponse === 'function' ? caughtException.getResponse() : null;

      if (caughtException instanceof HttpException) {
        status = caughtException.getStatus();
        responseContent = exceptionResponse;
      }

      if (typeof responseContent === 'object' && 'message' in responseContent) {
        errorMessage = responseContent.message;
      } else if (caughtException instanceof HttpException) {
        errorMessage = caughtException.message;
      }
    }

    this.logger.error(errorMessage, {
      status,
      req: getReqMainInfo(request),
      stack: caughtException.stack,
    });

    response.status(status).json({
      code: caughtException.code ?? status,
      error: caughtException.name,
      message: responseContent?.message || errorMessage,
      originUrl: request.originalUrl,
    });
  }
}